package com.spring.sunflower.common;

import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;

import com.spring.sunflower.R;
import com.spring.sunflower.base.BaseCompatActivity;
import com.spring.sunflower.constant.Constant;
import com.tencent.smtt.export.external.extension.interfaces.IX5WebSettingsExtension;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.util.HashMap;

/**
 * Created by Kevin on 2021/7/13<br/>
 * <p>
 * Describe:<br/>
 */
public class WebViewH5PayActivity extends BaseCompatActivity {
    private WebView mWebView;
    // 设置微信 H5 支付调用 loadDataWithBaseURL 的标记位，避免循环调用，
// 再次进入微信 H5 支付流程时记得重置此标记位状态
    boolean firstVisitWXH5PayUrl = true;
    private boolean shouldFinish = false;
    private String mReferer = "https://app.wanyuyue.cn";

    @Override
    public void initView() {
        String token = getField(Constant.KEY_TOKEN, "");
        String userID = getField(Constant.KEY_USERID, "");
        String currentEnvironment = getField(Constant.KEY_ENVIRONMENT, Constant.ENVIRONMENT_PRODUCT);
        Intent intent = getIntent();
//        String title = intent.getStringExtra(Constant.KEY_WEB_VIEW_TITLE);
//        String url = intent.getStringExtra(Constant.KEY_WEB_VIEW_URL);
        String mWebUrl = intent.getStringExtra("mWebUrl");
        if (currentEnvironment.equals(Constant.ENVIRONMENT_PRODUCT)) {
            mReferer = "https://app.wanyuyue.cn";//生产
        } else {
            mReferer = "http://www.wanyuyue.top";//测试
        }
//        String exchangeID = intent.getStringExtra("exchangeID");
//        String type = intent.getStringExtra("type");
//        String userIdOrMobile = intent.getStringExtra("userIdOrMobile");
        tvTitle.setText("微信支付");
//        String url = "http://www.wanyuyue.com?exchangeId=" + exchangeID + "&type=" + type + "&userIdOrMobile=" + userIdOrMobile;

        mWebView = findViewById(R.id.webView);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (TextUtils.isEmpty(url)) return false;
                try {
                    if (url.startsWith("weixin://wap/pay?") || url.startsWith("alipays://platformapi/startApp?")) {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(url));
                        startActivity(intent);
                        return true;
                    }
                } catch (Exception e) {
                    return false;
                }
                if (url.contains("wx.tenpay.com")) {
                    HashMap<String, String> map = new HashMap<>(1);
                    map.put("Referer", mReferer);
                    view.loadUrl(url, map);
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                String url = request.getUrl().toString();
                printD("shouldOverrideUrlLoading===" + url);
                if (TextUtils.isEmpty(url)) return false;
                try {
                    if (url.startsWith("weixin://wap/pay?") || url.startsWith("alipays://platformapi/startApp?")) {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(url));
                        startActivity(intent);
                        return true;
                    }
                } catch (Exception e) {
                    return false;
                }
                // 处理微信 H5 支付跳转时验证请求头 referer 失效
                // 验证不通过会出现“商家参数格式有误，请联系商家解决”
                if (url.contains("wx.tenpay.com")) {

                    // 申请微信 H5 支付时填写的域名
                    // 比如经常用来测试网络连通性的 http://www.baidu.com
//                    String referer = "http://www.wanyuyue.com";

                    // 兼容 Android 4.4.3 和 4.4.4 两个系统版本设置 referer 无效的问题
                    if (("4.4.3".equals(android.os.Build.VERSION.RELEASE))
                            || ("4.4.4".equals(android.os.Build.VERSION.RELEASE))) {
                        if (firstVisitWXH5PayUrl) {
                            view.loadDataWithBaseURL(mReferer, "<script>window.location.href=\"" + url + "\";</script>",
                                    "text/html", "utf-8", null);
                            // 修改标记位状态，避免循环调用
                            // 再次进入微信H5支付流程时记得重置状态 firstVisitWXH5PayUrl = true
                            firstVisitWXH5PayUrl = false;
                        }
                        // 返回 false 由系统 WebView 自己处理该 url
                        return false;
                    } else {
                        // HashMap 指定容量初始化，避免不必要的内存消耗
                        HashMap<String, String> map = new HashMap<>(1);
                        map.put("Referer", mReferer);
                        view.loadUrl(url, map);
                        return true;
                    }
                }
                return super.shouldOverrideUrlLoading(view, request);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
//                view.loadUrl("javascript:(function(){var objs = document.getElementsByTagName('img'); for(var i=0;i<objs.length;i++) {var img = objs[i];  img.style.maxWidth = '100%'; img.style.height = 'auto'; }})()");
            }
        });
        WebSettings webSetting = mWebView.getSettings();
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setDisplayZoomControls(false);
        webSetting.setUseWideViewPort(false);
        webSetting.setSupportMultipleWindows(false);
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setBlockNetworkImage(false);
        webSetting.setLoadWithOverviewMode(true);
        // 对于刘海屏机器如果webview被遮挡会自动padding

        IX5WebSettingsExtension settingsExtension = mWebView.getSettingsExtension();
        if (settingsExtension != null) {
            settingsExtension.setDisplayCutoutEnable(true);
        }

//        if (!TextUtils.isEmpty(url) && (url.endsWith(".jpg") || url.endsWith(".png"))) {
//            StringBuilder stringBuilder = new StringBuilder();
//            stringBuilder.append("<img  src=");
//            stringBuilder.append(url);
//            stringBuilder.append(">");
//            mWebView.loadDataWithBaseURL(null, stringBuilder.toString(), "text/html", "charset=UTF-8", null);
//            return;
//        }
//
        HashMap<String, String> map = new HashMap<>(1);
        map.put("Referer", mReferer);
//        view.loadUrl(url, map);
        mWebView.loadUrl(mWebUrl, map);
    }

    @Override
    public int getLayoutID() {
        return R.layout.activity_webview;
    }

    @Override
    protected void onResume() {
        if (shouldFinish) {
            finish();
        }
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        shouldFinish = true;
//        int i = AppUtils.appSize(this, "com.tencent.mm");
//        printD("appSize======" + i);
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//        if (getWindow().getDecorView().getVisibility() == View.VISIBLE) {
//            new Handler().postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    finish();
//                }
//            }, 2300);
//        } else {
//            finish();
//        }
//            }
//        },1200);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWebView != null) {
            mWebView.stopLoading();
            mWebView.setWebViewClient(null);
            mWebView.destroy();
        }
    }
}
